package com.mjk.common.web.getway.utils.loadbalancer.impl;

import com.mjk.common.web.getway.utils.loadbalancer.AbstractLoadBalancer;

import java.util.List;

/**
 * 加权轮询法
 */
public class WeightedRoundRobinLoadBalance extends AbstractLoadBalancer {
    private List<WeightedServer> weightedServers;
    private int totalWeight;
    private int currentIndex;

    public WeightedRoundRobinLoadBalance(List<WeightedServer> weightedServers) {
        this.weightedServers = weightedServers;
        totalWeight = calculateTotalWeight();
        currentIndex = 0;
    }

    private int calculateTotalWeight() {
        int total = 0;
        for (WeightedServer server : weightedServers) {
            total += server.getWeight();
        }
        return total;
    }

    public String getNextServer(String key) {
        int index = currentIndex;
        currentIndex = (currentIndex + 1) % totalWeight;
        return selectServer(index);
    }

    private String selectServer(int index) {
        for (WeightedServer server : weightedServers) {
            if (index < server.getWeight()) {
                return server.getName();
            }
            index -= server.getWeight();
        }
        return "";
    }
    static class WeightedServer {
        private String name;
        private int weight;

        public WeightedServer(String name, int weight) {
            this.name = name;
            this.weight = weight;
        }

        public String getName() {
            return name;
        }

        public int getWeight() {
            return weight;
        }
    }
}
